//
//  SPCityViewController.m
//  Sport
//
//  Created by Cass on 2017/11/14.
//  Copyright © 2017年 Cass. All rights reserved.
//

#import "SPCityViewController.h"

@interface SPCityViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *locationCityBtn;
@property (weak, nonatomic) IBOutlet UIView *headerView;

@property (nonatomic, strong) NSMutableDictionary *cities;
@property (nonatomic, strong) NSMutableArray *cityKeys;//城市首字母


@end

@implementation SPCityViewController


- (void)cityData{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"citydict.plist" ofType:nil];
    self.cities = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    [self.cityKeys addObjectsFromArray:[[self.cities allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBasic];
    [self cityData];

    
}

- (void)setBasic{
    self.cities = [NSMutableDictionary dictionary];
    self.cityKeys = [NSMutableArray array];
    [self.searchBar setBackgroundImage:[UIImage new]];
    [self.searchBar setSearchTextFieldTextColor:UIColorFromRGB(0x9a9a9a) placeholderColor:UIColorFromRGB(0x9a9a9a) backgroundColor:[UIColor whiteColor] borderColor:UIColorFromRGB(0xdddddd) cornerRadius:12];
    self.searchBar.tintColor = [UIColor blackColor];
    self.locationCityBtn.layer.borderColor = UIColorFromRGB(0x44A2FF).CGColor;
    self.locationCityBtn.layer.borderWidth = 1.0f;
    
    self.tableView.sectionIndexColor = [UIColor grayColor];
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
}

- (IBAction)locationCityBtnTapped:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(cityViewController:didSelectedCity:)]) {
        [self.delegate cityViewController:self didSelectedCity:[sender titleForState:UIControlStateNormal]];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchCity:(UISearchBar *)searchBar{
    if (searchBar.text.length > 0) {
        /**
         使用block同时遍历字典key，value
         block版本的字典遍历可以同时取key和value（forin只能取key再手动取value）
         */
        [_cities enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            for (NSString *cityName in obj) {
                if ([cityName rangeOfString:searchBar.text].length > 0) {
                    NSInteger section,row;
                    section = [_cityKeys indexOfObject:key];
                    row = [obj indexOfObject:cityName];
                    NSIndexPath *cityIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
                    [self.tableView scrollToRowAtIndexPath:cityIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
                }
            }
        }];
    }else{
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}
#pragma mark - UITableViewDataSource&&UITableViewDelegate -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _cityKeys.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSString *key = [_cityKeys objectAtIndex:section];
    NSArray *cityrows = [_cities objectForKey:key];
    return cityrows.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"cell";
    NSString *key = [_cityKeys objectAtIndex:indexPath.section];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.font = [UIFont systemFontOfSize:15.0f];
        cell.separatorInset = UIEdgeInsetsZero;//间隔线宽度
    }
    cell.textLabel.text = [[_cities objectForKey:key] objectAtIndex:indexPath.row];;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString *key = [_cityKeys objectAtIndex:section];
    return key;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return _cityKeys;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 32.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //在push-back回来之后,cell呈非选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *key = [_cityKeys objectAtIndex:indexPath.section];
    if ([self.delegate respondsToSelector:@selector(cityViewController:didSelectedCity:)]) {
        [self.delegate cityViewController:self didSelectedCity:[[_cities objectForKey:key]objectAtIndex:indexPath.row]];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - UISearchBarDelegate -
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [self searchCity:searchBar];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self searchCity:searchBar];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
